import { defineStore } from 'pinia'
import { queryMenuList } from "@/api/user"

let loginUser = JSON.parse(localStorage.getItem("loginUserInfo"));
export const useMainStore = defineStore('main', {
	state: () => {
		return {
			user: loginUser ? loginUser : null,
			menus: []
		}
	},
	actions: {
		login(user) {
			this.user = user;
			localStorage.setItem("loginUserInfo", JSON.stringify(user));
		},
		outLogin() {
			this.user = null;
			localStorage.removeItem("loginUserInfo");
		},
		getMenus() {
			return new Promise((resolve, reject) => {
				queryMenuList().then(res => {
					this.menus = res.result;

					const routerData = JSON.parse(JSON.stringify(res.result)) // 用于最后添加到 Router 中的数据
					const rewriteRoutes = filterAsyncRouter(routerData)

					resolve(rewriteRoutes)
				})
			})
		}
	}
})

// 遍历后台传来的路由字符串，转换为组件对象
function filterAsyncRouter(asyncRouterMap) {
	return asyncRouterMap.filter(route => {
		if (route.pid === 0) {
			route.component = () => import("@/layout/index.vue")
		}

		if (route.children) {
			filterAsyncRouter(route.children)
		} else { // 根节点
			route.component = loadView(route.components_path)
		}

		route.path = route.route_path;
		return true
	})
}

const loadView = (view) => { // 路由懒加载
	let modules = import.meta.glob('../views/**/*.vue')
	return modules[`../views/${view}.vue`]
}